<template>
  <div class="addTemp-mokuai">
    <div class="accounts-index">
      <div class="accounts-name">
        <div class="accounts-name-font">
          <span>{{ruleForm.modelId == null ? "添加":"编辑"}}模板</span>
          <div class="float-right">
            <el-button icon="el-icon-arrow-left" @click.native="returnButton" size="small">返回</el-button>
          </div>
        </div>
      </div>
      <div class="addTemp-content">
        <!-- 用户设置 -->
        <div class="addTemp-setting">
          <el-form
            :model="ruleForm"
            status-icon
            :rules="rules"
            ref="ruleForm"
            label-width="130px"
            class="demo-ruleForm"
          >
            <el-form-item label="模板名称 :" prop="modelName">
              <el-input v-model="ruleForm.modelName"></el-input>
            </el-form-item>

            <el-form-item label="费用计算方式 :" prop="pricingModel">
              <el-radio v-model="ruleForm.pricingModel" label="0">按重量计算</el-radio>
              <el-radio v-model="ruleForm.pricingModel" label="1">按商品件数计算</el-radio>
            </el-form-item>

            <el-form-item label="首重（kg）:" prop="firstWeight">
              <el-input v-model.number="ruleForm.firstWeight"></el-input>
            </el-form-item>

            <el-form-item label="首费（元）:" prop="firstExpense">
              <el-input v-model="ruleForm.firstExpense"></el-input>
            </el-form-item>

            <el-form-item label="续重（kg）:" prop="extendWeight">
              <el-input v-model.number="ruleForm.extendWeight"></el-input>
            </el-form-item>
            <el-form-item label="续费（元）:" prop="extendExpense">
              <el-input v-model="ruleForm.extendExpense"></el-input>
            </el-form-item>

            <el-form-item label="目的地 :" prop="regions">
              <el-select
                v-model="ruleForm.areaSelected1"
                placeholder="省"
                class="select-width"
                style="width:120px;"
              >
                <el-option
                  v-for="province in ruleForm.provinceList"
                  :key="province.id"
                  :label="province.name"
                  :value="province.id"
                ></el-option>
              </el-select>
              <el-select
                v-model="ruleForm.areaSelected2"
                placeholder="市"
                class="select-width margin-left"
                style="width:120px;"
              >
                <el-option
                  v-for="city in ruleForm.cityList"
                  :key="city.id"
                  :label="city.name"
                  :value="city.id"
                ></el-option>
              </el-select>
              <!-- <el-select v-model="ruleForm.areaSelected3" placeholder="区" class="select-width">
                <el-option
                  v-for="county in ruleForm.countyList"
                  :key="county.id"
                  :label="county.name"
                  :value="county.id"
                ></el-option>
              </el-select>-->
              <el-button @click="addRegions" type="text" size="small" class="margin-left">添加</el-button>
              <div style="padding-top:5px;">
                <el-tag
                  v-for="(region,index) in ruleForm.regions"
                  :key="index"
                  @close="handleClose(region)"
                  closable
                  effect="plain"
                  class="margin-right"
                >{{region}}</el-tag>
              </div>
            </el-form-item>
            <el-form-item class="button-center">
              <el-button type="primary" @click="submitForm('ruleForm')">提交</el-button>
            </el-form-item>
          </el-form>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 自定义 */
/* .select-width {
  width: 110px;
} */
.margin-left {
  margin-left: 10px;
}
.margin-right {
  margin-right: 10px;
}
.float-right {
  float: right;
}
.addTemp-mokuai {
  height: 700px;
  background-color: rgb(249, 249, 249);
  padding-top: 30px;
}
.accounts-index {
  width: 80%;
  margin: auto;
  background-color: rgb(255, 255, 255);
}
.accounts-name {
  width: 100%;
  height: 40px;
  background-color: rgb(240, 240, 240);
}
.accounts-name-font {
  height: 40px;
  line-height: 40px;
  margin-left: 20px;
  font-size: 14px;
  color: #666666;
}
.addTemp-content {
  width: 100%;
  height: 550px;
}

.addTemp-setting {
  margin-top: 20px;
  margin-left: 25%;
  width: 55%;
}

.button-center {
  margin-left: 20%;
}
</style>

<script>
import areaApi from "@/api/settings/area";
import freightApi from "@/api/settings/freight";
export default {
  data() {
    var validateWeight = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("不能为空"));
      }
      setTimeout(() => {
        if (!Number.isInteger(value)) {
          callback(new Error("输入的不是数字！"));
        } else {
          // if (value < 40) {
          //   callback(new Error("单位kg请修改js"));
          // } else {
          //   callback();
          // }
          // 验证后一定得调用callback()回调函数
          callback();
        }
      }, 1000);
    };
    var validateExpense = (rule, value, callback) => {
      var reg = /(^[1-9]([0-9]+)?(\.[0-9]{1,2})?$)|(^(0){1}$)|(^[0-9]\.[0-9]([0-9])?$)/;
      if (!value) {
        return callback(new Error("不能为空"));
      }
      setTimeout(() => {
        if (!reg.test(value)) {
          callback(new Error("输入的金额格式不正确！例子：18.20"));
        } else {
          // if (value < 15) {
          //   callback(new Error("单位元请修改js"));
          // } else {
          //   callback();
          // }
          // 验证后一定得调用callback()回调函数
          callback();
        }
      }, 1000);
    };
    // var validateExtendWeight = (rule, value, callback) => {
    //   if (value === "") {
    //     callback(new Error("单位kg请修改js"));
    //   } else {
    //     if (this.ruleForm.extendExpense !== "") {
    //       this.$refs.ruleForm.validateField("extendExpense");
    //     }
    //     callback();
    //   }
    // };
    // var validateExtendExpense = (rule, value, callback) => {
    //   if (value === "") {
    //     callback(new Error("单位元请修改js"));
    //   } else if (value !== this.ruleForm.pass) {
    //     callback(new Error("单位元请修改js"));
    //   } else {
    //     callback();
    //   }
    // };

    return {
      // 表单
      ruleForm: {
        modelId: null,
        modelName: "默认模板",
        pricingModel: 0,
        firstWeight: "",
        firstExpense: "",
        extendWeight: "",
        extendExpense: "",
        areaSelected1: null,
        areaSelected2: null,
        provinceList: [],
        cityList: [],
        region: "",
        regions: []
      },
      rules: {
        modelName: [
          { required: true, message: "请输入模板名称", trigger: "blur" },
          { min: 3, max: 6, message: "长度在 3 到 6 个字符", trigger: "blur" }
        ],
        pricingModel: [{ required: true }],
        regions: [
          { required: true, message: "请选择目的地区域", trigger: "blur" }
        ],
        firstWeight: [
          { required: true, validator: validateWeight, trigger: "blur" }
        ],
        firstExpense: [
          { required: true, validator: validateExpense, trigger: "blur" }
        ],
        extendWeight: [
          { required: true, validator: validateWeight, trigger: "blur" }
        ],
        extendExpense: [
          { required: true, validator: validateExpense, trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    // 返回
    returnButton() {
      this.$router.replace({ path: "/settings/freightTemp" });
    },
    // 提交信息
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          let temp = "";
          this.ruleForm.regions.forEach((item, index) => {
            if (index == 0) {
              temp = item;
            } else {
              temp += ";" + item;
            }
          });
          let template = {
            id: this.ruleForm.modelId,
            name: this.ruleForm.modelName,
            pricingModel: this.ruleForm.pricingModel,
            firstWeight: this.ruleForm.firstWeight,
            firstExpense: this.ruleForm.firstExpense,
            extendWeight: this.ruleForm.extendWeight,
            extendExpense: this.ruleForm.extendExpense,
            region: temp
          };
          if (this.ruleForm.modelId === null) {
            freightApi.addFreight(template).then(() => {
              this.$router.replace({ path: "/settings/freightTemp" });
            });
          } else {
            freightApi.updateById(template).then(() => {
              this.$router.replace({ path: "/settings/freightTemp" });
            });
          }
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    // 初始化区域设置 获取所有区域信息
    initArea() {
      areaApi.findLayeredAreas(2).then(response => {
        this.ruleForm.provinceList = response.data.data;
      });
    },
    // 当有数据时初始化form表单
    initForm() {
      let template = this.$route.params.template;
      if (template !== undefined) {
        this.ruleForm.modelId = template.id;
        this.ruleForm.modelName = template.name;
        this.ruleForm.pricingModel = template.pricingModel;
        this.ruleForm.firstWeight = template.firstWeight;
        this.ruleForm.firstExpense = template.firstExpense;
        this.ruleForm.extendWeight = template.extendWeight;
        this.ruleForm.extendExpense = template.extendExpense;
        this.ruleForm.regions = template.region.split(";");
      }
    },
    // 添加目的地区域
    addRegions() {
      if (this.ruleForm.region === "") {
        this.$message({
          showClose: true,
          message: "出错了，目的地为空！",
          type: "error"
        });
      } else if (
        this.ruleForm.regions.filter(item => item == this.ruleForm.region)
          .length == 0
      ) {
        //在数组最后 添加数据
        this.ruleForm.regions.splice(
          this.ruleForm.regions.length,
          0,
          this.ruleForm.region
        );
      } else {
        this.$message({
          showClose: true,
          message: "出错了，目的地已存在！",
          type: "error"
        });
      }
    },
    // 删除已选目的地区域
    handleClose(tag) {
      this.ruleForm.regions.splice(this.ruleForm.regions.indexOf(tag), 1);
    }
  },
  watch: {
    // 深度监听 对象的属性 ："对象.属性"
    "ruleForm.areaSelected1": {
      handler: function(newVal) {
        if (newVal != null) {
          // this.ruleForm.region = newVal;
          this.ruleForm.cityList = this.ruleForm.provinceList.filter(
            item => item.id === newVal
          )[0].children;
          this.ruleForm.areaSelected2 = null;
        }
      }
    },
    "ruleForm.areaSelected2": {
      handler: function(newVal) {
        if (newVal != null) {
          this.ruleForm.region = this.ruleForm.cityList.filter(
            item => item.id === newVal
          )[0].name;
          // this.ruleForm.regions[this.ruleForm.regions.length] = cityName;
          // if(this.ruleForm.region.length > 0){
          //   this.ruleForm.region +=";"+ cityName;
          // }else{
          //   this.ruleForm.region += cityName;
          // }
        }
      }
    }
  },
  created() {
    this.initForm();
    this.initArea();
  }
};
</script>